// 引入模块
var express = require('express');
var webpack = require('webpack');
var path = require('path');
var app = express();
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var consolidate = require('consolidate');
var env = process.env.NODE_ENV || "development";

var router = express.Router();

router.get('*', function (req, res) {
  res.render('index'); 
});

app.engine('html', consolidate.ejs);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, './client/view'));

var config;
if (env === 'production') { //生产环境
  config = require('./webpack.config');
  var compiler = webpack(config);
  app.use(express.static(path.join(__dirname, 'client/static/dist')));
  console.log('生产环境');

} else if (env === 'development') { //开发环境
  config = require('./webpack.config.dev');
  var compiler = webpack(config);

  app.use(webpackDevMiddleware(compiler, {
    // public path should be the same with webpack config
    publicPath: config.output.publicPath,
    noInfo: true,
    stats: {
      colors: true
    }
  }));
  app.use(webpackHotMiddleware(compiler));
  console.log('开发环境');
} else {
  console.log('Please define NODE_ENV first\nlinux & mac: export NODE_ENV=production(or development)\nwindows: set NODE_ENV=production(or development\n)');
}

app.use('/', router);

// 启动一个服务，监听从8080端口进入的所有连接请求
var server = app.listen(8080, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Listening at http://%s:%s', host, port);
});